﻿using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WSYmi.BleService;

namespace WSYmi.MainAct
{
    /// <summary>
    /// 主要作用与服务的连接发生更改时通知客户端
    /// </summary>
    public class BleServiceConnection : Java.Lang.Object, IServiceConnection
    {
        static string TAG { get; } = typeof(BleServiceConnection).FullName;

        public bool IsConnected { get; private set; }

        public BleBinder Binder { get; private set; }

        private IServiceConnection MainActivity { get; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="activity"></param>
        public BleServiceConnection(MainActivity activity)
        {
            IsConnected = false;
            Binder = null;
            MainActivity = activity;
        }


        /// <summary>
        /// 客户端与服务器已连接
        /// </summary>
        /// <param name="name"></param>
        /// <param name="service"></param>
        public void OnServiceConnected(ComponentName name, IBinder service)
        {
            Binder = service as BleBinder;
            IsConnected = Binder != null;

            string message = "onServiceConnected - ";
            Log.Debug(TAG, $"OnServiceConnected {name.ClassName}");

            if (IsConnected)
            {
                message = message + " bound to service " + name.ClassName;
                MainActivity.OnServiceConnected(name, service);
            }
            else
            {
                message = message + " not bound to service " + name.ClassName;
            }

            Log.Info(TAG, message);
        }

        /// <summary>
        /// 客户端与服务器的连接断开
        /// </summary>
        /// <param name="name"></param>
        public void OnServiceDisconnected(ComponentName name)
        {
            MainActivity.OnServiceDisconnected(name);
            IsConnected = false;
            Binder = null;
        }
    }
}